package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.LoginFormDTO;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.User;
import com.hmdp.mapper.UserMapper;
import com.hmdp.service.IUserService;
import com.hmdp.utils.RegexPatterns;
import com.hmdp.utils.RegexUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    private final UserMapper userMapper;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    public UserServiceImpl(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    @Override
    public Result sendCode(String phone, HttpSession session) {
        //校验用户手机号
        if (RegexUtils.isPhoneInvalid(phone)){
           return Result.fail("手机号不合法");
        }
        //生成验证码
        String code = RandomUtil.randomNumbers(4);
        //redis缓存验证码
        ValueOperations value = stringRedisTemplate.opsForValue();
        value.set(LOGIN_CODE_KEY + phone, code, LOGIN_CODE_TTL, TimeUnit.MINUTES);
        session.setAttribute("code",code);
        log.info("发送验证码:"+code);
        return Result.ok();
    }

    @Override
    public Result login(LoginFormDTO loginForm, HttpSession session) {
        String phone = loginForm.getPhone();
        String password = loginForm.getPassword();
        if (RegexUtils.isPhoneInvalid(phone)){
            return Result.fail("手机号不合法");
        }
        //String code = (String) session.getAttribute("code");
        ValueOperations value = stringRedisTemplate.opsForValue();
        String code = (String) value.get(LOGIN_CODE_KEY + phone);
        if (code == null || !code.equals(loginForm.getCode())){
            return  Result.fail("验证码错误");
        }

        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone",phone);
        User user = userMapper.selectOne(queryWrapper);
        if (user == null){
           user = createUser(phone,password);
        }
        //保存用户信息到Session
        //session.setAttribute("user",user);
        //保存用户信息到Redis中
        UserDTO userDTO = new UserDTO();
        BeanUtil.copyProperties(user,userDTO);
        HashOperations hash = stringRedisTemplate.opsForHash();
        Map<String, Object> map = BeanUtil.beanToMap(userDTO,new HashMap<>(),
                CopyOptions.create().setIgnoreNullValue(true).setFieldValueEditor((fileName,fileValue)->fileValue.toString()));
        String token = UUID.randomUUID().toString(true);
        String tokenKey = LOGIN_USER_KEY + token;
        hash.putAll(tokenKey,map);
        stringRedisTemplate.expire(tokenKey,LOGIN_USER_TTL, TimeUnit.MINUTES);
        return Result.ok(tokenKey);
    }

    private User createUser(String phone, String password) {
        User user = new User();
        user.setPhone(phone);
        user.setPassword(password);
        int insert = userMapper.insert(user);
        if (insert != 1){
            return null ;
        }
        return user;
    }
}
